#include "rel.h"

/**
 * Parses a received Ack message. 
 *
 * @param A pointer to the array storing the message.
 *
 */
 
int parseAckMessage() {
	
	// Extract sequence number
	  // Append Sequence Number into message (in network order)
  void * ptr = (void * ) &receiveMessageBuffer[1];
  unsigned long long * longPtr = (unsigned long long * ) ptr;
  unsigned long long receivedSequenceNumber = htonll(*longPtr);  
  
  if(debug)
		puts("Trying to parse");
  
  if (debug) {
  		printf("CURRENT SEQ NUM: %lld\n", currentSequenceNumber);
  		printf("RECEIVED SEQ NUM: %lld\n", receivedSequenceNumber);

  }
  
  // Compare against current sequence number
  if (currentSequenceNumber == (receivedSequenceNumber - 1) ) {
  	
  	// Increment sequence number
  	currentSequenceNumber ++;
  	if (debug) {
  		printf("CURRENT SEQ NUM: %lld\n", currentSequenceNumber);
  		printf("RECEIVED SEQ NUM: %lld\n", receivedSequenceNumber);

  	}

  	createDataMessage();
  
  }
  
  else {
  	return 0;
  }
  
  
  // If it's +1 higher than current sequence number, then:
  // Compose next data packet
  // Send next data packet
  
  // If ACK is not correct, then retransmit data message sitting in 
  // send message queue
  
  // return true if ACK is correct, false if this is not the
  // correct ACK.
  return 0;
}

/**
 * Creates an Ack message.
 *
 * @param sequenceNumber - acknowledges the next sequence number expected
 * @return int - size of the message (length)
 */
int createAckMessage(unsigned long long sequenceNumber) {
  
  // Append Sequence Number into message (in network order)
  void * ptr = (void * ) &sendMessageBuffer[1];
  unsigned long long * longPtr = (unsigned long long * ) ptr;
  
  // Lock sendMessageBuffer
  pthread_mutex_lock ( &mutexLock ); 
  
  // Write identifier  
  sendMessageBuffer[0] = 0xAA;
  
  *longPtr = htonll(sequenceNumber);  
  
  // Write window size
  sendMessageBuffer[9] = 0x00;
  
  // Message Size
  sendMessageSize = 1 + 8 + 1;
  // UNLock sendMessageBuffer
  pthread_mutex_unlock ( &mutexLock ); 
  
  
  if (debug) {
    printMessage(sendMessageBuffer, sendMessageSize);
  }
  
  return sendMessageSize;
}
 